from datetime import datetime
from functools import cached_property
from pathlib import Path
from typing import ClassVar
from pydantic import BaseModel
import polars as pl
from pysam import tabix_compress, tabix_index  # pylint: disable=E0611


DATA_DIR = Path(__file__).parent / "data"


class PrepareBase(BaseModel):
    name: ClassVar[str]
    header: ClassVar[str]
    input_file: Path
    outdir: Path

    @cached_property
    def output_bed(self) -> Path:
        return self.outdir / f"{self.name}.{datetime.now().strftime('%Y%m%d')}.bed"

    @property
    def output_gz(self) -> Path:
        return self.output_bed.with_suffix(".bed.gz")

    def read_input(self) -> pl.DataFrame:
        raise NotImplementedError("Not Implemented")

    def run(self):
        self.outdir.mkdir(exist_ok=True, parents=True)
        dataframe = self.read_input()
        with open(self.output_bed, "w") as writer:
            writer.write(f"{self.header}\n")
            writer.write(dataframe.write_csv(separator="\t", include_header=False))
        tabix_compress(str(self.output_bed), str(self.output_gz), force=True)
        tabix_index(str(self.output_gz), force=True, preset="bed")
        self.output_bed.unlink(missing_ok=True)
